
const {findArticle} = require('../service/article.service')

const {
  articleFormateError,
  articleIdFormateError,
  articleDoesNotExist,
  articleAlreadyExited,
  articleInsertError
} = require('../constant/err.type')

// 验证文章是否为空
const articleValidator = async (ctx, next) => {
  const {title} = ctx.request.body;
  if(!title) {
    console.error('文章名为空', ctx.request.body)
    ctx.response.body = articleFormateError
    return
  }
  await next()
}

// 验证文章id是否为空
const articleIdValidator = async (ctx, next) => {
  const {id} = ctx.request.body;
  if(!id) {
    console.error('文章id为空', ctx.request.body)
    ctx.response.body = articleIdFormateError
    return
  }
  await next()
}

// 验证文章id是不存在
const articleIdHas = async (ctx, next) => {
  const {id} = ctx.request.body;
  try {
    const res = await findArticle({id})
    if(!res || res.length === 0 ) {
      console.error('不存在此文章id', ctx.request.body)
      ctx.response.body = articleDoesNotExist
      return
    }
  } catch(err) {
    console.log('获取文章信息错误', err)
    ctx.response.body = articleInsertError
    return
  }
  await next()
}


// 验证文章存在
const hasArticle = async (ctx, next) => {
  const {id, title} = ctx.request.body;
  try {
    const res = await findArticle({title})
    if(res && res.length > 0) {
      console.error('该文章已经存在，请勿重复添加！', ctx.request.body)
      ctx.response.body = articleAlreadyExited
      return
    } 
  } catch(err) {
    console.error('获取文章信息错误', err)
    ctx.response.body = articleInsertError
    return
  }

  await next()
 
}

module.exports = {articleValidator, articleIdValidator, hasArticle, articleIdHas}